package com.os.controller;


import cn.hutool.core.util.ObjectUtil;
import com.os.exception.Asserts;
import com.os.model.DataSource;
import com.os.ops.Obj;
import com.os.result.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;


/**
 * @author 风亦未止
 * @date 2023/5/2 0:12
 */
@RestController
@RequestMapping("/dataServer")
public class ObjController {
    @Autowired
    private Obj obj;

    /**
     * 对象数据传输，过时
     * @param hash
     * @param dataSource
     * @return
     */
    @PutMapping("/{hash}")
    @Deprecated
    public Resp put(@PathVariable("hash") String hash , @RequestPart("file") MultipartFile dataSource) {
        boolean put = obj.put(hash, dataSource);
        if(put){
            return Resp.success(null, "操作成功！");
        }
        return Resp.failed();
    }

    @GetMapping("/{hash}")
    public ResponseEntity<InputStreamResource> get(@PathVariable("hash") String hash){
        if(StringUtils.isEmpty(hash)){
            Asserts.fail("hash为空~");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        FileInputStream readStream = obj.getReadStream(hash);
        if(ObjectUtil.isNull(readStream)){
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        InputStreamResource resource = new InputStreamResource(readStream);
        return ResponseEntity.ok().body(resource);
    }



}
